﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WorkFlowCore.Authorization;
using WorkFlowCore.Host.ViewModels;
using WorkFlowCore.Host.ViewModels.WorkFlowCore;
using WorkFlowCore.UserSelectors;
using WorkFlowCore.Workflows;
using WorkFlowCore.WorkTasks;
using Mapster;
using WorkFlowCore.IRepositories;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Application.Dtos;
using Microsoft.AspNetCore.Authorization;
using WorkFlowCore.Conditions;
using WorkFlowCore.Framework.UserSelectors;
using System.Linq.Expressions;
using WorkFlowCore.FormDesigns;
using WorkFlowCore.Common.Tracers;
using WorkFlowCore.Host.ViewModels.FormDesigns;

namespace WorkFlowCore.Host.Controllers
{
    /// <summary>
    /// 流程相关
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    [Obsolete("已拆分到 FlowDesignController 和 WorkFTaskController")]
    public class WorkFlowController : AbpControllerBase
    {
        private ConditionManager conditionManager;
        private UserSelectorManager userSelectorManager;
        private WorkflowManager workflowManager;
        private WorkTaskManager workTaskManager;
        private IWorkflowRepository workflowRepository;
        private IWorkTaskRepository worktaskRepository;
        private IBasicRepository<WorkflowVersionInfo, Guid> versionRepository;
        private IBasicRepository<WorkStepInfo, Guid> workStepRepository;
        private IWorkflowSession workflowSession;
        private StepForecastManager stepForecastManager;
        private FormDesignManager formDesignManager;


        public WorkFlowController(ConditionManager conditionManager, WorkflowManager workflowManager, IWorkflowRepository workflowRepository, IWorkTaskRepository worktaskRepository, IBasicRepository<WorkflowVersionInfo, Guid> versionRepository, IBasicRepository<WorkStepInfo, Guid> workStepRepository, IWorkflowSession workflowSession, WorkTaskManager workTaskManager, UserSelectorManager userSelectorManager, StepForecastManager stepForecastManager, FormDesignManager formDesignManager)
        {
            this.conditionManager = conditionManager;
            this.workflowManager = workflowManager;
            this.workflowRepository = workflowRepository;
            this.worktaskRepository = worktaskRepository;
            this.versionRepository = versionRepository;
            this.workStepRepository = workStepRepository;
            this.workflowSession = workflowSession;
            this.workTaskManager = workTaskManager;
            this.userSelectorManager = userSelectorManager;
            this.stepForecastManager = stepForecastManager;
            this.formDesignManager = formDesignManager;
        }
        /// <summary>
        /// 获取所有条件项
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAllconditions")]
        public async Task<IEnumerable<ConditionDto>> GetAllconditions()
        {
            return conditionManager.AllConditions.Select(c => new ConditionDto { Id = c.Id, Name = c.Name, Description = c.Description, Enabled = c.Enabled });
        }
        /// <summary>
        /// 获取所有的用户选择器
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAllUserSelectors")]
        public async Task<IEnumerable<UserSeletorDto>> GetAllUserSelectors()
        {
            return userSelectorManager.UserSelectors.Select(us => new UserSeletorDto { Id = us.Id, Name = us.Name, Description = us.Description, Enabled = us.Enabled });
        }
        /// <summary>
        /// 根据用户选择器获取用户选项（大类）
        /// </summary>
        /// <param name="userSelectorId">用户选择器标识</param>
        /// <returns></returns>
        [HttpGet("GetUserSelectionsOfUserSelector")]
        public async Task<List<Selection>> GetUserSelectionsOfUserSelector(string userSelectorId)
        {
            using (var activity = WorkflowActivitySource.Source?.StartActivity("GetUserSelectionsOfUserSelector"))
            {
                return await workTaskManager.GetUserSelectionsOfUserSelector(userSelectorId);
            }
                
        }

        /// <summary>
        /// 根据用户选项（大类）获取用户列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("GetUsersOfUserSelecton")]
        public async Task<List<Selection>> GetUsersOfUserSelecton([FromQuery] GetUsersOfUserSelectonInput input)
        {
            return await userSelectorManager.GetUsersOfUserSelecton(input.userSelectorId, input.InputSelectionIds);
        }

        /// <summary>
        /// 创建新流程设计
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("CreateWorkFlow")]
        public async Task<Workflow> CreateWorkFlow(CreateWorkFlowInput input)
        {
            return await workflowManager.CreateWorkflow(input.Name, input.Des, input.Type);
        }
        /// <summary>
        /// 获取所有流程设计（包含版本）列表
        /// 用于在表单设计时筛选流程设计版本
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAllWorkflowsWithDefaultVersion")]
        public async Task<List<GetAllWorkflowsWithVersionOutput>> GetAllWorkflowsWithDefaultVersion()
        {
            return (await workflowRepository.GetListAsync())
                .OrderByDescending(w=>w.IsLock)
                .OrderByDescending(w => w.Name).Select(w => new GetAllWorkflowsWithVersionOutput
            {
                ActiveVersion = w.ActiveVersion,
                Id = w.Id,
                Name = w.Name,
                WorkflowNo = w.WorkflowNo
            }).ToList();
        }
        /// <summary>
        /// 获取流程所有版本信息
        /// </summary>
        /// <param name="workflowId"></param>
        /// <returns></returns>
        [HttpGet("GetAllWorkflowVersions")]
        public async Task<IEnumerable<GetAllWorkflowVersionOutput>> GetAllWorkflowVersions(Guid workflowId)
        {
            return (await versionRepository.GetListAsync(v => v.WorkflowId == workflowId)).Select(v => new GetAllWorkflowVersionOutput
            {
                WorkflowId = v.WorkflowId,
                VersionNo = v.VersionNo,
                Description = v.Description,
                CreationTime = v.CreationTime,
                ModifiedTime = v.ModifiedTime,
                IsLock = v.IsLock,
            }).OrderBy(w => w.VersionNo);
        }
        /// <summary>
        /// 获取流程具体版本信息
        /// </summary>
        /// <param name="versionNo">版本编号</param>
        /// <param name="id">设计id</param>
        /// <returns></returns>
        [HttpGet("GetWorkflowVersion")]
        public async Task<GetWorkflowVersionOutput> GetWorkflowVersion(int versionNo, Guid id)
        {
            var version = await workflowManager.GetWorkflowVersion(id, versionNo);
            return version.Adapt<GetWorkflowVersionOutput>();
        }

        /// <summary>
        /// 根据任务id获取流程具体版本信息
        /// </summary>
        /// <param name="workTaskId">任务id</param>
        /// <returns></returns>
        [HttpGet("GetWorkflowVersionByTaskId")]
        public async Task<GetWorkflowVersionOutput> GetWorkflowVersionByTaskIdAsync(Guid workTaskId)
        {
            var task = await workTaskManager.GetWorkTaskAsync(workTaskId);
            if(task==null) return null;
            var version = await workflowManager.GetWorkflowVersion(task.WorkflowId.Id, task.WorkflowId.VersionNo);
            return version.Adapt<GetWorkflowVersionOutput>();
        }

        /// <summary>
        /// 删除流程
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("Delete")]
        public async Task<bool> Delete(Guid id)
        {
            var result = await workflowManager.DeleteWorkflow(id);
            return result;
        }

        /// <summary>
        /// 删除流程版本
        /// </summary>
        /// <param name="id">设计id</param>
        /// <param name="versionNo">版本编号</param>
        /// <returns></returns>
        [HttpDelete("DeleteWorkflowVersion")]
        public async Task<bool> DeleteWorkflowVersion(Guid id, int versionNo)
        {
            var result = await workflowManager.DeleteWorkflowVersion(id, versionNo);
            return result;
        }
        /// <summary>
        /// 更新流程激活的版本
        /// </summary>
        /// <param name="input"></param>
        [HttpPut("UpdateWorkflowActiveVersion")]
        public async Task<bool> UpdateWorkflowActiveVersion(UpdateWorkflowActiveVersionInput input)
        {
            var result = await workflowManager.UpdateWorkflowActiveVersion(input.WorkflowId, input.ActiveVersion);
            return result;
        }


        /// <summary>
        /// 更新流程
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut("UpdateWorkFlow")]
        public async Task<Workflow> UpdateWorkFlow(UpdateWorkFlowInput input)
        {
            return await workflowManager.UpdateWorkflow(input.WorkflowId.Id, input.Name, input.Des, input.Type, input.WorkflowId.VersionNo, input.DrawingInfo, input.VersionDescription
                , input.WorkflowLines.Select(line => new WorkflowLine(line.Name, input.WorkflowId, line.FromNodeId, line.ToNodeId, line.Conditions)).ToList()
                , input.WorkflowNodes.Select(node => new WorkflowNode(node.Id, input.WorkflowId, node.Name, node.NodeType, node.DrawingInfo, node.IsWaitingAllUser, node.UserSelectors, node.RejectNodes, node.ProveMode,node.IsAutoHandleSameUserStep,node.IsIgnoreCreator)).ToList());
        }

        /// <summary>
        /// 获取所有流程列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAllWorkflows")]
        public async Task<PageResult<WorkflowDto>> GetAllWorkflows([FromQuery] GetAllWorkflowInput input)
        {

            var items = await workflowRepository.GetPagedListAsync(w => !w.Deleted && (input.Name.IsNullOrWhiteSpace() || w.Name.Contains(input.Name)), input.SkipCount, input.MaxResultCount, "IsLock desc, ModifiedTime desc");
            var count = await workflowRepository.GetCountAsync(w => !w.Deleted && (input.Name.IsNullOrWhiteSpace() || w.Name.Contains(input.Name)));
            var workflowIds = items.Select(i => i.Id).ToArray();
            var versionCount = await workflowRepository.GetWorkflowVersionCount(workflowIds);

            var wf4formDesign = items.Select(i => new WorkflowId4FormDesign(i.Id, i.ActiveVersion)).ToArray();
            var activeFromVersion = await formDesignManager.GetFormDesignsOfWorkflowId(wf4formDesign);
            var result = new PageResult<WorkflowDto>
            {
                Items = items.Select(i =>
            {
                var itemOut = i.Adapt<WorkflowDto>();
                itemOut.VersionCount = versionCount.GetOrDefault(itemOut.Id);
                itemOut.ActiveFormVersion = activeFromVersion.FirstOrDefault(af => af.WorkflowId.Id == itemOut.Id && af.WorkflowId.Version == itemOut.ActiveVersion)?.ActiveVersion ?? 0;
                return itemOut;
            }).ToList(),
                Total = count
            };
            return result;
        }
        /// <summary>
        /// 创建流程任务
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("CreateWorkTaskWithDefaultVersion")]
        public async Task<WorkTask> CreateWorkTaskWithDefaultVersion(CreateWorkTaskWithDefaultVersionInput input)
        {
            input.CreatedUserId = workflowSession.User.Id;
            var worktask = await workTaskManager.CreateWorkTaskWithDefaultVersion(input.WorkflowId, input.Name, input.FormData, input.EntityFullName, input.EntityKeyValue, input.CreatedUserId,input.FormLink);
            return worktask;
        }
        /// <summary>
        /// 创建流程任务
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("CreateWorkTask")]
        public async Task<WorkTask> CreateWorkTask(CreateWorkTaskInput input)
        {
            input.CreatedUserId = workflowSession.User.Id;
            var worktask = await workTaskManager.CreateWorkTask(input.WorkflowId, input.Name, input.FormData, input.EntityFullName, input.EntityKeyValue, input.CreatedUserId, input.FormLink);
            return worktask;
        }

        /// <summary>
        /// 创建流程任务
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("CreateSimulationWorkTask")]
        public async Task<WorkTask> CreateSimulationWorkTask(CreateWorkTaskInput input)
        {
            input.CreatedUserId = workflowSession.User.Id;
            var worktask = await workTaskManager.CreateSimulationWorkTask(input.WorkflowId, input.Name, input.FormData, input.EntityFullName, input.EntityKeyValue, input.CreatedUserId, input.FormLink);
            return worktask;
        }

        /// <summary>
        /// 获取流程任务
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("GetWorkTask")]
        public async Task<WorkTask> GetWorkTask(Guid id)
        {
            var worktask = await workTaskManager.GetWorkTaskAsync(id);
            return worktask;
        }

        /// <summary>
        /// 获取流程任务（根据关联的业务表单标识获取流程审批）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("GetWorkTaskByEntityInfo")]
        public async Task<WorkTask> GetWorkTaskByEntityInfo([FromQuery] GetWorkTaskByEntityInfoInput input)
        {
            var workTaskInfo = await worktaskRepository.GetAsync(w => w.EntityFullName == input.EntityFullName && w.EntityKeyValue == input.EntityKeyValue);
            var worktask = workTaskInfo.ToWorkTask();
            return worktask;
        }

        /// <summary>
        /// 发起流程
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("StartWorkTask")]
        public async Task<List<WorkStep>> StartWorkTask(StartWorkTaskInput input)
        {
            var steps = await workTaskManager.WorkTaskStart(input.WorktaskId);
            return steps;
        }
        /// <summary>
        /// 通过审批
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("PassProve")]
        public async Task<List<WorkStep>> PassProve(ProveInput input)
        {
            var proveResult = await workTaskManager.PassApprove(input.StepId, input.Comment, input.ResourceIds, input.FormData);
            if (proveResult.Code == ProveResult.ProveResultCode.FAIL)
                throw new Exception(proveResult.Msg);
            return proveResult.WorkSteps;
        }
        /// <summary>
        /// 驳回审批
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("RejectProve")]
        public async Task<List<WorkStep>> RejectProve(RejectProveInput input)
        {
            var proveResult = await workTaskManager.RejectApprove(input.StepId, input.Comment, input.ResourceIds, input.FormData, input.RejectToNodeId);
            if (proveResult.Code == ProveResult.ProveResultCode.FAIL)
                throw new Exception(proveResult.Msg);
            return proveResult.WorkSteps;
        }
        /// <summary>
        /// 撤回审批（撤回处理的审批）
        /// 只能在下一节点的用户未读前撤回。
        /// ***不建议使用该操作，如需重新审批，建议沟通下一节点审批人驳回然后再处理。***
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("WithdrawProve")]
        public async Task<List<WorkStep>> WithdrawProve(ProveInput input)
        {
            var proveResult = await workTaskManager.Withdraw(input.StepId, input.Comment);
            if (proveResult.Code == ProveResult.ProveResultCode.FAIL)
                throw new Exception(proveResult.Msg);
            return proveResult.WorkSteps;
        }
        /// <summary>
        /// 转发代办
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("ForwardProve")]
        public async Task<List<WorkStep>> ForwardProve(ForwardProveInput input)
        {
            var proveResult = await workTaskManager.Forward(input.StepId, input.UserSelectors, input.users, input.Comment);
            if (proveResult.Code == ProveResult.ProveResultCode.FAIL)
                throw new Exception(proveResult.Msg);
            return proveResult.WorkSteps;
        }
        /// <summary>
        /// 获取所有审批步骤
        /// </summary>
        /// <param name="worktaskId"></param>
        /// <returns></returns>
        [HttpGet("GetAllTaskStepsOfWorkTask")]
        public async Task<List<WorkStep>> GetAllTaskStepsOfWorkTask(Guid worktaskId)
        {
            //获取所有过程输出
            var historySteps = await workTaskManager.GetAllTaskStepsOfWorkTaskAsync(worktaskId);
            return historySteps;
        }

        /// <summary>
        /// 获取用户待审批步骤
        /// </summary>
        /// <param name="worktaskId"></param>
        /// <returns></returns>
        [HttpGet("GetPenddingTaskStepsOfWorkTask")]
        public async Task<List<WorkStep>> GetPenddingTaskStepsOfWorkTask(Guid worktaskId)
        {
            //获取所有过程输出
            var steps = await workTaskManager.GetPenddingTaskStepsOfWorkTaskAsync(worktaskId);
            return steps;
        }
        /// <summary>
        /// 清除模拟 记录
        /// </summary>
        /// <returns></returns>
        [HttpPost("ClearSimulationRecord")]
        public async Task<object> ClearSimulationRecord()
        {
            await workTaskManager.ClearSimulationRecord();

            return OutputDto.Succeed<object>(null);
        }

        /// <summary>
        /// 获取所有用户（仅模拟用户）
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAllUserForSimulation")]
        public async Task<List<UserSelectors.User>> GetAllUserForSimulation()
        {
            return UserList.Users.Select(u => new UserSelectors.User { Id = u.Id, Name = u.Name }).ToList();
        }

        /// <summary>
        /// 获取所有审批步骤：根据关联的业务表单标识获取
        /// </summary>
        /// <param name="entityFullName">表单类型</param>
        /// <param name="entityKeyValue">表单标识</param>
        /// <returns></returns>
        [HttpGet("GetAllTaskStepsOfWorkTaskByEntityInfo")]
        public async Task<List<WorkStep>> GetAllTaskStepsOfWorkTaskByEntityInfo(string entityFullName, string entityKeyValue)
        {
            //获取所有过程输出
            var historySteps = await workTaskManager.GetAllTaskStepsOfWorkTaskByEntityInfoAsync(entityFullName, entityKeyValue);
            return historySteps;
        }



        private async Task FillWorktaskInfo<TWorkTaskDto>(List<TWorkTaskDto> workTasks) where TWorkTaskDto : WorkTaskDto
        {
            var workflows = await workflowRepository.GetListAsync(w => workTasks.Select(s => s.WorkflowId.Id).Contains(w.Id));
            workTasks.ForEach(i =>
            {
                i.WorkflowId.WorkflowName = workflows.FirstOrDefault(w => w.Id == i.WorkflowId.Id)?.Name;
            });
        }

        /// <summary>
        /// 获取用户待处理的流程
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetUnHandledWorkTasksOfUser")]
        public async Task<PageResult<HandleWorkTaskDto>> GetUnHandledWorkTasksOfUser([FromQuery] GetUnHandledWorkTasksOfUserInput input)
        {
            var worktasks = await workTaskManager.GetUnHandledWorkTasksOfUserAsync(workflowSession.User.Id, input.CurrentPage, input.MaxResultCount);
            var result = new PageResult<HandleWorkTaskDto>
            {
                Items = worktasks.Items.Select(i => i.Task).Adapt<List<HandleWorkTaskDto>>(),// mapper.Map<List<WorkTask>, List<WorkTaskDto>>(worktasks.Items),
                Total = worktasks.Total
            };

            for (int i = 0; i < result.Items.Count; i++)
            {
                result.Items[i].WorkStepType = worktasks.Items[i].Step.WorkStepType;
                result.Items[i].IsHandled = worktasks.Items[i].Step.IsHandled;
                result.Items[i].HandleType = worktasks.Items[i].Step.HandleType;
                result.Items[i].IsRead = worktasks.Items[i].Step.IsRead;
            }
            await FillWorktaskInfo(result.Items);

            return result;

        }

        /// <summary>
        /// 获取用户已处理的流程
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetHandledWorkTasksOfUser")]
        public async Task<PageResult<HandleWorkTaskDto>> GetHandledWorkTasksOfUser([FromQuery] GetHandledWorkTasksOfUserInput input)
        {
            var worktasks = await workTaskManager.GetHandledWorkTasksOfUserAsync(workflowSession.User.Id, input.CurrentPage, input.MaxResultCount);
            var result = new PageResult<HandleWorkTaskDto>
            {
                Items = worktasks.Items.Select(i => i.Task).Adapt<List<HandleWorkTaskDto>>(),// mapper.Map<List<WorkTask>, List<WorkTaskDto>>(worktasks.Items),
                Total = worktasks.Total
            };
            for (int i = 0; i < result.Items.Count; i++)
            {
                result.Items[i].WorkStepType = worktasks.Items[i].Step.WorkStepType;
                result.Items[i].IsHandled = worktasks.Items[i].Step.IsHandled;
                result.Items[i].HandleType = worktasks.Items[i].Step.HandleType;
                result.Items[i].IsRead = worktasks.Items[i].Step.IsRead;
            }
            await FillWorktaskInfo(result.Items);

            return result;
        }
        /// <summary>
        /// 根据实体类型（业务表单类型）获取所有的处理中的工作流
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet("GetAllProcessingWorkTasksByEntityType"), AllowAnonymous]
        public async Task<List<WorkTask>> GetAllProcessingWorkTasksByEntityType([FromQuery] GetAllProcessingWorkTasksByEntityTypeInput input)
        {
            var worktaskInfos = await worktaskRepository.GetListAsync(wt => input.EntityKeyValues.Contains(wt.EntityKeyValue) && !wt.Deleted && wt.EntityFullName == input.EntityFullName);
            return worktaskInfos.Select(wt => wt.ToWorkTask()).ToList();
        }
        /// <summary>
        /// 获取当前用户创建的流程
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("GetWorkTasksOfCreator")]
        public async Task<PageResult<WorkTaskDto>> GetWorkTasksOfCreator([FromQuery] GetWorkTasksOfCreatorInput input)
        {
            var worktasks = await worktaskRepository.GetWorkTasksOfCreatorAsync(workflowSession.User.Id, input.CurrentPage, input.MaxResultCount);
            var result = new PageResult<WorkTaskDto>
            {
                Items = worktasks.Items.Adapt<List<WorkTaskDto>>(), //mapper.Map<List<WorkTask>, List<WorkTaskDto>>(worktasks.Items),
                Total = worktasks.Total
            };

            await FillWorktaskInfo(result.Items);

            return result;
        }
        /// <summary>
        /// 获取所有审批流程
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("GetAllWorkTasks")]
        public async Task<PageResult<WorkTaskDto>> GetAllWorkTasks([FromQuery] GetAllWorkTasksInput input)
        {
            var worktasks = await worktaskRepository.GetAllWorkTasksAsync(input.CurrentPage, input.MaxResultCount);
            var result = new PageResult<WorkTaskDto>
            {
                Items = worktasks.Items.Adapt<List<WorkTaskDto>>(), //mapper.Map<List<WorkTask>, List<WorkTaskDto>>(worktasks.Items),
                Total = worktasks.Total
            };

            await FillWorktaskInfo(result.Items);

            return result;
        }
        /// <summary>
        /// 获取（当前节点）驳回节点
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("GetRejectNodes")]
        public async Task<List<WorkflowNodeDto>> GetRejectNodes([FromQuery] GetRejectNodesInput input)
        {
            var data = await workTaskManager.GetRejectNodes(input.WorkStepId);
            var result = data.Adapt<List<WorkflowNodeDto>>();
            return result;
        }
        /// <summary>
        /// 取消审批流程（撤回发起审批）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut("CancelWorkTask")]
        public async Task<WorkTaskDto> CancelWorkTask(IdInput input)
        {
            var workTaskInfo = await worktaskRepository.GetAsync(input.Id);
            var workTask = workTaskInfo.ToWorkTask();
            workTask.Cancel();
            await worktaskRepository.UpdateAsync(workTask.ToWorkTaskInfo(workTaskInfo));
            var result = workTask.Adapt<WorkTaskDto>();
            return result;
        }
        /// <summary>
        /// 复制审批任务
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("CopyWorkTask")]
        public async Task<WorkTaskDto> CopyWorkTask(IdInput input)
        {
            var workTaskInfo = await worktaskRepository.GetAsync(input.Id);
            var workTask = workTaskInfo.ToWorkTask();
            var newWorkTask = workTask.Copy();
            await worktaskRepository.InsertAsync(newWorkTask.ToWorkTaskInfo());
            var result = newWorkTask.Adapt<WorkTaskDto>();
            return result;
        }

        /// <summary>
        /// 获取所有流程列表（带版本信息）
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAllWorkflowsWithVersion")]
        public async Task<List<GetAllWorkflowsWithVersionOutput>> GetAllWorkflowsWithVersion()
        {
            var workflows = await workflowManager.GetAllWorkflowsWithVersion();
            return workflows.Adapt<List<GetAllWorkflowsWithVersionOutput>>();
        }
        /// <summary>
        /// 删除审批任务
        /// </summary>
        /// <returns></returns>
        [HttpDelete("DeleteWorkTask")]
        public async Task DeleteWorkTaskAsync(Guid id)
        {
            await workTaskManager.DeleteWorkTask(id);
        }

        /// <summary>
        /// 更新流程表单
        /// </summary>
        /// <returns></returns>
        [HttpPut("UpdateWorkTaskFormData")]
        public async Task UpdateWorkTaskFormData(UpdateWorkTaskFormDataInput input)
        {
            var workTaskInfo = await worktaskRepository.GetAsync(input.Id);
            if (workTaskInfo == null) return;
            var workTask = workTaskInfo.ToWorkTask();
            workTask.UpdateFormData(input.FormData);
            await worktaskRepository.UpdateAsync(workTask.ToWorkTaskInfo(workTaskInfo));
        }
        /// <summary>
        /// 获取审批任务的预测节点用户
        /// </summary>
        /// <param name="taskId"></param>
        /// <returns></returns>
        [HttpGet("GetForecastNodeUsers4Task")]
        public async Task<List<ForecastNodeUserOutput>> GetForecastNodeUsers(Guid taskId)
        {
            var users = await stepForecastManager.GetForecastNodeUsers(taskId);
            return MapForecastNodeUserDto(users);
        }
        /// <summary>
        /// 获取流程设计的预测节点用户（用于发起发起审批前）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("GetForecastNodeUsers4Workflow")]
        public async Task<List<ForecastNodeUserOutput>> GetForecastNodeUsers(GetForecastNodeUsers4WorkflowInput input)
        {
            var users = await stepForecastManager.GetForecastNodeUsers(new WorkflowId(input.VersionNo, input.workflowId), input.formData);
            return MapForecastNodeUserDto(users);
        }
        private static List<ForecastNodeUserOutput> MapForecastNodeUserDto(List<ForecastNodeUser> users)
        {
            return (users ?? new List<ForecastNodeUser>()).Select(u => new ForecastNodeUserOutput
            {
                HandleType = u.HandleType,
                Level = u.Level,
                NodeId = u.NodeId,
                NodeName = u.NodeName,
                IsWaitingAllUser = u.IsWaitingAllUser,
                HandleUsers = (u.HandleUsers ?? new List<ForecastUser>()).Select(hu => new ForecastUserDto
                {
                    HandleType = hu.HandleType,
                    Id = hu.Id,
                    Name = hu.Name,
                    WorkStepType = hu.WorkStepType,
                    Comment = hu.Comment,
                    ResourceIds = hu.ResourceIds,
                    HandlerTime = hu.HandlerTime,

                }).OrderBy(h=>h.HandlerTime).ToList(),
                ReadOnlyUsers = (u.ReadOnlyUsers ?? new List<ForecastUser>()).Select(hu => new ForecastUserDto
                {
                    HandleType = hu.HandleType,
                    Id = hu.Id,
                    Name = hu.Name,
                    WorkStepType = hu.WorkStepType,
                    Comment = hu.Comment,
                    ResourceIds = hu.ResourceIds,
                    HandlerTime = hu.HandlerTime,

                }).OrderBy(h => h.HandlerTime).ToList(),
                Users = (u.Users ?? new List<ForecastUser>()).Select(hu => new ForecastUserDto
                {
                    HandleType = hu.HandleType,
                    Id = hu.Id,
                    Name = hu.Name,
                    WorkStepType = hu.WorkStepType,
                    Comment = hu.Comment,
                    ResourceIds = hu.ResourceIds,
                    HandlerTime = hu.HandlerTime,

                }).OrderBy(h => h.HandlerTime).ToList()
            }).ToList();
        }

        /// <summary>
        /// 创建新流程设计或者更新流程设计
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("CreateOrUpdateWorkFlow")]
        public async Task<Workflow> CreateOrUpdateWorkFlow(UpdateWorkFlowInput input)
        {
            return await workflowManager.CreateUpdateWorkflow(input.WorkflowId.Id, input.Name, input.Des, input.Type, input.WorkflowId.VersionNo, input.DrawingInfo, input.VersionDescription
                , input.WorkflowLines.Select(line => new WorkflowLine(line.Name, input.WorkflowId, line.FromNodeId, line.ToNodeId, line.Conditions)).ToList()
                , input.WorkflowNodes.Select(node => new WorkflowNode(node.Id, input.WorkflowId, node.Name, node.NodeType, node.DrawingInfo, node.IsWaitingAllUser, node.UserSelectors, node.RejectNodes, node.ProveMode,node.IsAutoHandleSameUserStep,node.IsIgnoreCreator)).ToList());
        }

        /// <summary>
        /// 锁定流程设计版本（锁定后不允许编辑）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("LockWorkflowVersion")]
        public async Task<bool> LockWorkflowVersion(LockWorkflowVersionInput input)
        {
            if(input==null)
            {
                return false;
            }
            return await workflowManager.LockWorkflowVersion(input.id, input.versionNo);
        }

        /// <summary>
        /// 锁定流程设计
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("LockWorkflow")]
        public async Task<bool> LockWorkflow(LockWorkflowInput input)
        {
            if (input == null)
            {
                return false;
            }
            return await workflowManager.LockWorkflow(input.id);
        }
    }
}
